package it.okkam.webid.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletContext;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;

import edu.mit.simile.longwell.LongwellServer;
import edu.mit.simile.longwell.ui.FlairMessage;

public class DataModel {
	
	protected ServletContext context;
	
/**
 * Save the user to the ttl / rdf store
 * @param msg
 */
	public void writeOutPutModel(FlairMessage msg, Model inputModel) {

		context = msg.m_servlet.getServletContext();
		String outputDatasetFileName = LongwellServer.getUsersDatasetPath();
		Model usersModel = LongwellServer.getBCCDataset().getNamedModel("http://www.provincia.tn.it/bcc/resource/bcc-utenti");
		usersModel.add(inputModel);
		usersModel.commit();
		//versione vecchia che scriveva gli utenti su un file ttl.
		//adesso invece si scrivono le informazioni su triplestore
		/*
		OutputStream out = null;
		try {
			out = new FileOutputStream(new File(outputDatasetFileName));
			inputModel.write(out, "TURTLE");
			out.close();
		} catch (FileNotFoundException e) {
			System.out.println("File: " + outputDatasetFileName + " not found");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
	}
// generate the hash of a password
	public static String generateHash(String input) {

		input = input + "RIVELA";

		StringBuilder hash = new StringBuilder();

		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = sha.digest(input.getBytes());
			char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'a', 'b', 'c', 'd', 'e', 'f' };
			for (int idx = 0; idx < hashedBytes.length; ++idx) {
				byte b = hashedBytes[idx];
				hash.append(digits[(b & 0xf0) >> 4]);
				hash.append(digits[b & 0x0f]);
			}
		} catch (NoSuchAlgorithmException e) {
			// handle error here.
		}

		return hash.toString();
	}

}
